package reading.util.aes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * @author TXW
 * @version V1.0
 * @Title: ${file_name}
 * @date 2018/11/15 10:06
 */
public class PwdEncoder {
    private final static Logger logger = LoggerFactory.getLogger(PwdEncoder.class);
    private final static String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static final String ALGORITHM = "MD5";

    public static String encode(String salt, String rawPass) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM);
            //加密后的字符串
            result = byteArrayToHexString(md.digest(mergePasswordAndSalt(salt, rawPass).getBytes("utf-8")));
        } catch (Exception ex) {
            logger.error("加密失败", ex);
        }
        return result;
    }


    private static String mergePasswordAndSalt(String salt, String password) {
        if (password == null) {
            password = "";
        }

        if ((salt == null) || "".equals(salt)) {
            return password;
        } else {
            return password + "{" + salt + "}";
        }
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
     * 哈希盐
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM);
            md.update(str.getBytes());
            byte[] b = md.digest();
            int i;
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
        } catch (Exception e) {
            logger.error("md5 加密失败");
        }
        return str;
    }
}
